from mitmproxy import ctx
import pandas as pd
import openpyxl
from db_opetaror import db_operator
import datetime
from read_config import read_config
import operate_tools

"""运行前先清空表里的数据"""
db_operator.delete_all_data()



data_list = []


def response(flow):
    # 提取请求的URL
    url = flow.request.url

    if "rce-api" in url or "xypopo-extend" in url or "workbench" in url:
        db_opa = db_operator(url)
        db_opa.insert_api_record_data()
        # 提取请求方法
        method = flow.request.method
        #获取当前时间
        timer = str(datetime.datetime.now())
        if not db_opa.judge_data_exists():
            db_opa.insert_api_record_count_data()
        else:
            update_time = db_opa.get_update_time()
            #获取时间差
            diff_time = operate_tools.diff_time_seconds(update_time, timer)
            #读取时间配置
            time_config = read_config.get_timer()
            if diff_time < time_config:
                db_opa.update_latest_id_count_add_one()
            else:
                db_opa.update_latest_id_tense_finished()
                db_opa.insert_api_record_count_data()



        # 提取响应状态码
        status_code = flow.response.status_code
        # 提取响应内容
        response_content = flow.response.content
        # 提取响应内容长度
        content_length = len(flow.response.content)

        # 将数据添加到列表
        data_list.append([url, method, status_code, response_content, content_length])

        # 将数据转换为DataFrame
        df = pd.DataFrame(data_list, columns=['URL', 'Method', 'Status Code', 'response_content', 'Content Length'])

        # 将数据保存到CSV文件
        df.to_excel('.\\network_data.xlsx', index=False, engine='openpyxl')
